
/*
 _______________#########_______________________
 ______________############_____________________
 ______________#############____________________
 _____________##__###########___________________
 ____________###__######_#####__________________
 ____________###_#######___####_________________
 ___________###__##########_####________________
 __________####__###########_####_______________
 ________#####___###########__#####_____________
 _______######___###_########___#####___________
 _______#####___###___########___######_________
 ______######___###__###########___######_______
 _____######___####_##############__######______
 ____#######__#####################_#######_____
 ____#######__##############################____
 ___#######__######_#################_#######___
 ___#######__######_######_#########___######___
 ___#######____##__######___######_____######___
 ___#######________######____#####_____#####____
 ____######________#####_____#####_____####_____
 _____#####________####______#####_____###______
 ______#####______;###________###______#________
 ________##_______####________####______________
 葱官赐福  百无禁忌

 // 				 _ooOoo_
 // 		  	    o8888888o
 // 	  	  	    88" . "88
 //                 (| -_- |)
 //                  O\ = /O
 //              ____/`---*\____
 //               . * \\| |// `.
 //             / \\||| : |||// \
 //           / _||||| -:- |||||- \
 //             | | \\\ - /// | |
 //            | \_| **\---/** | |
 //           \  .-\__ `-` ___/-. /
 //            ___`. .* /--.--\ `. . __
 //        ."" *< `.___\_<|>_/___.* >*"".
 //      | | : `- \`.;`\ _ /`;.`/ - ` : | |
 //         \ \ `-. \_ __\ /__ _/ .-` / /
 //======`-.____`-.___\_____/___.-`____.-*======
 // `=---=*
 //
 // .............................................
 //              佛祖保佑 永无BUG


 */
var express = require('express');
var lyby = require('../util');
var router = express.Router();
var userModel = require('../models/emlog_user');

var request = require('request');
var url = require('url');
var querystring = require('querystring');
var commonHost500pxAPI = __IPOnline//'123.57.68.250:8093';//8093测试环境的

var errorMsg = '';

var getUserInfo = function (req,res,next) {
    return new Promise(function (resolve, reject) {
        var urlStr = url.format({
            protocol: 'http',
            host: 'design.shijue.me',
            pathname: '/page/login/userinfo',
            //host: 'usercenter.500px.me',
            //pathname: '/app/appLogin.do'
        });
        request.post({
            url: urlStr,
            headers: {
                // Cookie : '_ga=GA1.2.167994531.1508736397; _gid=GA1.2.1030544571.1520409280; userId=15f8dbf6d417aa75823d32e6906c14051_d; Hm_lvt_7acfbc4d7bdb93be5cf0ee26c52160bf=1519874586,1519961784,1520505694; Hm_lpvt_7acfbc4d7bdb93be5cf0ee26c52160bf=1520505694; token=Token-4a185037-6126-4e74-8949-c9ff45ea5b41',
                Cookie : local.cookie || req.headers.cookie,
                'User-Agent': req.headers['user-agent']//'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
            },/*,
             headers: {
             Cookie : 'JSESSIONID=b1ps9btstunalkm2f0t91o8u;',
             Host : 'photo-test-community.shijue.me',
             'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
             Referer : 'http://photo-test-community.shijue.me'
             }*/
        }, function (err, msg, data) {
            // console.log(err)
            // console.log("***" + data);
            try{
                var VCG = JSON.parse(data);
                // eval(data);
                // resolve("Hello");
                resolve(VCG);
                // reject(VCG);
            }catch (e){
                reject({
                    status : 500,
                    message : '获取用户信息失败，测试环境JAVA重启了。'
                })
            }
        });
    });
}
var user_class = function(req, res, next) {
    var _handler = function () {
        next();
        // var loginUser = req.session.userinfo;
        // if(loginUser.id){
        //     console.log('成功登录');
        //     next();
        // }else{
        //     console.log('没登录');
        //     res.json(req.session.userinfo);
        //     console.log(888)
        // }
    }
    if (!req.session.userinfo) {//未登录或者没有权限
        getUserInfo.apply(this,arguments).then(function (msg) {
            // console.log(msg)
            // req.session.user_token = data.userAccountInfo.access_token;
            // req.session.user_id = data.userAccountInfo.userId;
            // req.session.userName = data.userAccountInfo.userName;

            req.session.userinfo = msg;
            //这个变量在util.js里用
            global.SJ_UT = msg;
            _handler();
        },function (msg) {
            //请求失败
            console.log(msg)
            // res.json(msg);
            _handler();
        })
        //res.locals = {title: '用户登陆', layout: 'login/layout' , qqLoginUrl:'/qq/login',errorMsg:errorMsg};
        // res.render('login/index');
        // res.send('同有登陆');
        // /page/login/userinfo
    } else {
        //console.log('登录了');
        // next();
        _handler();
    }
    errorMsg = '';
};
user_class.lxx = function(req, res, next) {
    if (!req.session.user_id || !req.session.userInfor ) {//未登录或者没有权限 || !req.session.userInfor.permMap.back
        //console.log('没登录');

        res.locals = {title: '用户登陆', layout: 'login/layout' , qqLoginUrl:'/qq/login',errorMsg:errorMsg};
        console.log(1188);
        res.render('login/index2');
        console.log(1199);
    } else {
        //console.log('登录了');
        next();
    }
    errorMsg = '';
};
/* GET users listing. */
router.get('/', user_class,function(req, res, next){
    res.redirect('/');
});
router.get('/init', function (req, res, next) {
    //需要登录,做不了了
    if(req.query.cookie){
        global.__JSESSIONID = 'JSESSIONID='+req.query.cookie;
    }else{
        delete global.__JSESSIONID;
    }
    res.status(200).send('');
});
//注销
router.get('/logout', function (req, res, next) {
    req.session.destroy();
    //res.redirect('/');    现改为跳转到退出前的页面。理论上是到首页的
    if(req.headers.referer){
        res.redirect(req.headers.referer);
    }else{
        res.redirect('/');
    }
});
user_class.logout=function(req, res, next){
    errorMsg = this.msg;
    req.session.destroy();
    res.render('login/index',{title: '用户登陆', layout: 'login/layout' , qqLoginUrl:'/qq/login',errorMsg:errorMsg});
};

router.post('/getUserInfo', function (req, res, next) {
    res.json(req.session.userInfor?req.session.userInfor:{
        userName :  req.session.userName,
        userId :  req.session.user_id
    });
});
router.post('/restartTest',user_class,function(req, res, next){
    var exec = require('child_process').exec;
    var cmdStr = 'cd /data/1/usr/local/applications/test-PageRender-file-online/nodejs-500px;git pull;';
    var flag = req.body.indexFlag;
    exec(cmdStr, function(err,stdout,stderr){
        if(err) {
            console.log('cmd is error:'+stderr);
            res.json({
                errmesage : 'error le'
            });
        } else {
            console.log(stdout);
            res.json({
                code : 200
            });
            if(flag == '500px_online'){
                exec('forever restart bin/www_online',function(){});
            }else{
                exec('forever restart bin/www_test',function(){});
            }

        }
    });
});


/*以下都是post请求 begin*/
//登录
router.post('/login2', function (req, res, next) {
    var urlStr = url.format({
        protocol: 'https',
        host: '500px.me',
        pathname: '/user/v2/tologin',
        //host: 'usercenter.500px.me',
        //pathname: '/app/appLogin.do'
    });
    request.post({
        json : true,
        qs : {
            userName : req.body.username,
            password : req.body.password,
            expires : __timeout
        },
        url: urlStr,
        headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
        },/*,
         headers: {
         Cookie : 'JSESSIONID=b1ps9btstunalkm2f0t91o8u;',
         Host : 'photo-test-community.shijue.me',
         'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
         Referer : 'http://photo-test-community.shijue.me'
         }*/
    }, function (err, msg, data) {
        if(err)throw err;
        lyby.info('用户登录成功:');
        lyby.info(data);

        if(data.status == 401){
            errorMsg = '帐户名密码有误!';
            res.redirect('/users')
        }else if(data.status == 200){
            req.session.user_token = data.userAccountInfo.access_token;
            req.session.user_id = data.userAccountInfo.userId;
            req.session.userName = data.userAccountInfo.userName;


            var urlStr = url.format({
                protocol: 'http',
                host: commonHost500pxAPI,
                pathname: '/back/user/userInfo'
            });

            request.get({
                url: urlStr,
                json: true,
                qs: {
                    accessToken : req.session.user_token,
                    userInfo :''
                }
            }, function (err, msg, data) {
                if (err)throw err;

                //这里手动给相关用户添加大赛后台的权限
                var tempData = data.data;
                var permObj = {
                    '15f8dbf6d417aa75823d32e6906c14051' : '15f8dbf6d417aa75823d32e6906c14051',
                    'c35cca62649229c485dc725f372947612' : 'c35cca62649229c485dc725f372947612',
                    '4e9f6c33a465381f82250dc853b3f8985' : '4e9f6c33a465381f82250dc853b3f8985',
                    '7b8f92c1c453f8bfc9d8f2f7a25261663' : '7b8f92c1c453f8bfc9d8f2f7a25261663'
                };
                if(permObj[tempData.userProperty.userId]){
                    tempData.permMap.back = true;
                    data.data = tempData;
                }
                req.session.userInfor = data.data;
                lyby.info('用户详细信息:');
                lyby.info(data);//记录一下用户登录信息
                if(req.session.userInfor.permMap.back){
                    res.json(data);
                    /*res.redirect(req.headers.referer);*/
                }else{
                    res.json(data);
                }

            });

            //res.locals = {title: '用户登陆', layout: 'login/layout' , qqLoginUrl:'/qq/login',errorMsg:errorMsg};
            //console.log(11);
            //res.render('error_pages/nopermission');
            //console.log(22);
            //

            //res.redirect(req.headers.referer);
            if(!data.user){
                data.user = data.userAccountInfo || {};
            }
            if(userModel.mode){
                userModel.model.find({userid:data.user.userId},function (err,list) {
                    // finds people with surname='Doe', skips first 2 and limits to 3 elements,
                    // returning only 'name' and 'surname' properties
                    if(!list.length){
                        userModel.model.create({
                            userid: data.user.userId,
                            username: req.body.username,
                            password: lyby.md5(req.body.password),
                            nickName: data.user.nickName,
                            mobile: data.user.mobile,
                            regTime: data.user.regTime,
                            loginTime: new Date(),
                            email: data.user.email,
                            level: data.user.admin,
                            vcginfo: data.user
                        },function(){

                        });
                    }else{
                        list[0].save({ loginTime: new Date() }, function (err) {
                        });
                    }
                });
            }
            //http://usercenter.500px.me/getUserInfo?ticket=你登录成功后返回的token
            /*var urlStr = url.format({
             protocol: 'http',
             host: 'usercenter.500px.me',
             pathname: '/getUserInfo'
             });
             request.post({
             json : true,
             qs : {
             access_token : data.access_token
             //ticket : data.ticket
             },
             url: urlStr
             }, function (err, msg, data) {
             if(err)throw err;
             if(data.status == 301){
             errorMsg = '超时退出!';
             res.redirect('/logout')
             }else if(data.status == 200){
             //res.json(data);
             req.session.user_id = data.userId;
             res.redirect(req.headers.referer);
             }
             });*/
        }else {
            errorMsg = '帐户名密码有误!';
            res.redirect('/users')
        }
    });

    /*以前自己写的用户登录
     userModel.model.find({
     username : req.body.username,
     password : lyby.md5(req.body.password)
     },function(err, people){
     if(people.length){
     req.session.user_id = req.body.username;
     res.redirect(req.headers.referer);
     }else{
     errorMsg = '登失败了';
     res.redirect('/users');
     }
     });*/
});

/*以下都是post请求 begin*/
//登录
router.post('/login', function (req, res, next) {
    var urlStr = url.format({
        protocol: 'https',
        host: '500px.me',
        pathname: '/user/v2/tologin',
        //host: 'usercenter.500px.me',
        //pathname: '/app/appLogin.do'
    });
    request.post({
        json : true,
        qs : {
            userName : req.body.username,
            password : req.body.password,
            expires : __timeout
        },
        url: urlStr/*,
        headers: {
            Cookie : 'JSESSIONID=b1ps9btstunalkm2f0t91o8u;',
            Host : 'photo-test-community.shijue.me',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
            Referer : 'http://photo-test-community.shijue.me'
        }*/
    }, function (err, msg, data) {
        if(err)throw err;
        if(data.status == 200){
            req.session.user_token = data.userAccountInfo.access_token;
            req.session.user_id = data.userAccountInfo.userId;
            req.session.userName = data.userAccountInfo.userName;




            request.get({
                url: urlStr,
                json: true,
                qs: {
                    accessToken : req.session.user_token,
                }
            }, function (err, msg, data) {
                if (err)throw err;
                //res.json(data);
                res.redirect(req.headers.referer);
            });

            //res.locals = {title: '用户登陆', layout: 'login/layout' , qqLoginUrl:'/qq/login',errorMsg:errorMsg};
            //console.log(11);
            //res.render('error_pages/nopermission');
            //console.log(22);
            //

            //res.redirect(req.headers.referer);
            if(!data.user){
                data.user = data.userAccountInfo || {};
            }
            if(userModel.mode){
                userModel.model.find({userid:data.user.userId},function (err,list) {
                    // finds people with surname='Doe', skips first 2 and limits to 3 elements,
                    // returning only 'name' and 'surname' properties
                    if(!list.length){
                        userModel.model.create({
                            userid: data.user.userId,
                            username: req.body.username,
                            password: lyby.md5(req.body.password),
                            nickName: data.user.nickName,
                            mobile: data.user.mobile,
                            regTime: data.user.regTime,
                            loginTime: new Date(),
                            email: data.user.email,
                            level: data.user.admin,
                            vcginfo: data.user
                        },function(){

                        });
                    }else{
                        list[0].save({ loginTime: new Date() }, function (err) {
                        });
                    }
                });
            }
            //http://usercenter.500px.me/getUserInfo?ticket=你登录成功后返回的token
            /*var urlStr = url.format({
             protocol: 'http',
             host: 'usercenter.500px.me',
             pathname: '/getUserInfo'
             });
             request.post({
             json : true,
             qs : {
             access_token : data.access_token
             //ticket : data.ticket
             },
             url: urlStr
             }, function (err, msg, data) {
             if(err)throw err;
             if(data.status == 301){
             errorMsg = '超时退出!';
             res.redirect('/logout')
             }else if(data.status == 200){
             //res.json(data);
             req.session.user_id = data.userId;
             res.redirect(req.headers.referer);
             }
             });*/
        }else{
            //(data.status == 401)
            errorMsg = '帐户名密码有误!';
            res.redirect('/users')
        }
    });

    /*以前自己写的用户登录
    userModel.model.find({
        username : req.body.username,
        password : lyby.md5(req.body.password)
    },function(err, people){
        if(people.length){
            req.session.user_id = req.body.username;
            res.redirect(req.headers.referer);
        }else{
            errorMsg = '登失败了';
            res.redirect('/users');
        }
    });*/
});
//注册
/*router.post('/signup', function (req, res, next) {
    //查询用户是否已注册
    userModel.model.find({username: req.body.username}, function (err, people) {
        if (err) throw err;
        if (!people.length) {
            //将密码加密
            req.body.password = lyby.md5(req.body.password);
            //创建新用户
            userModel.model.create(req.body, function (error) {
                if (error){
                    errorMsg = error.message||'注册失败，联系管理员！';
                    res.redirect(req.headers.referer||'/users');
                    return;
                }
                req.session.user_id = req.body.username;
                res.redirect('/');
            });
        }else{
            //,{title: '注册失败',layout:'login/layout'}
            errorMsg = '用户名已存在，请重新注册';
            res.redirect(req.headers.referer||'/users');
        }
    });
});*/
/*以下都是post请求 end*/
user_class.router = router;
module.exports = user_class;
